package com.ruoyi.web.controller.PhoneLogin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.service.PhoneLoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.ruoyi.common.config.Global.getConfig;

public class WxService {

    private Logger logger = LoggerFactory.getLogger(WxService.class);

    private static String SEND_URL = "https://api.weixin.qq.com/cgi-bin/message/custom/send";

    @Autowired
    private WeChatJSSDKController weChatJSSDKController;


    @Autowired
    private PhoneLoginService phoneLoginService;


    private  String appids=getConfig("weixin4j.appids");

    private  String appsecret=getConfig("weixin4j.secrets");

    private  String mch_id=getConfig("weixin4j.mch_id");

    private  String MerchantKey=getConfig("weixin4j.MerchantKey");

    public String acceptMessage(HttpServletRequest request, HttpServletResponse response) {
//        {CreateTime=1548042266, Event=user_enter_tempsession, ToUserName=gh_e6198220cbff,
//                FromUserName=oZvme4q2Oi7Dz3FChXc43kqw28, MsgType=event, SessionFrom=wxapp}
        String respMessage = "";
        try {
            // xml请求解析
            Map<String, String> requestMap = MessageUtil.parseXml(request);
            logger.info(">>>>>>>>>>>>>"+requestMap);
            // 发送方帐号（open_id）
            String fromUserName = requestMap.get("FromUserName");
            // 公众帐号
            String toUserName = requestMap.get("ToUserName");
            // 消息类型
            String msgType = requestMap.get("MsgType");
            //人工服务
            String content = requestMap.get("Content");
            List<Map<String, Object>> list =  phoneLoginService.CallShellProcedure("R2005009");
            Map<String, Object> sss=list.get(0);
            String t1 = sss.get("newDate").toString();
            String t2 = getBeforeByHourTime(1);
            DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            String accessToken="";
            if(sdf.parse(t1).getTime()>sdf.parse(t2).getTime()){
                accessToken=sss.get("access_token").toString();
            }else {
                //access_token不在有效期
                try {
                    accessToken =weChatJSSDKController.getAccessToken();
                    phoneLoginService.CallShellProcedure("R2005010|"+accessToken);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            //此处我默认为直接人工服务  可根据实际业务调整
            return switchCustomerService(fromUserName,toUserName,requestMap);
/*            //小程序客服 文本信息
           if(msgType.equals("text")){
                if("人工服务".equals(content)){
                    HashMap<String, Object> resultMap = new HashMap<>();
                     resultMap.put("ToUserName",fromUserName);
                     resultMap.put("FromUserName",toUserName);
                     resultMap.put("CreateTime", requestMap.get("CreateTime"));
                     resultMap.put("MsgType","transfer_customer_service");
                     String json = JSON.toJSONString(resultMap);
                     JSONObject result = JSONObject.parseObject(json);
                     logger.info("POST   result"  +  result);
                     return result;
                }
                sendCustomerTextMessage(fromUserName,"你好，欢迎使用人工服务",accessToken);
            }else if(msgType.equals("event")){//会话功能
                String sessionFrom = (String) requestMap.get("SessionFrom");
                logger.info("SessionFrom   SessionFrom"  +  sessionFrom);
                int i = sessionFrom.indexOf("+");
                String sessionFromFirst = "1";

                if( i > 0){
                    sessionFromFirst = sessionFrom.substring(0, i); //标志位 1 2 3 4 5 6
                    logger.info("SessionFrom   sessionFromFirst    "  +  sessionFromFirst);
                    String sessionFromLast = sessionFrom.substring(i+1);  //{"appId":"","data":"test"}
                    logger.info("SessionFrom   sessionFromLast     "  +  sessionFromLast);
                    if(JSONObject.parseObject(sessionFromLast).get("appId") != null){
                        appId = (String) JSONObject.parseObject(sessionFromLast).get("appId");
                    }
                    sendCustomerTextMessage(fromUserName,"你好，欢迎使用会话服务",accessToken);
                }
            }else if(msgType.equals("image")){
                logger.info("公众号接受图片..........");
                sendCustomerImageMessage(fromUserName,requestMap.get("MediaId"),accessToken);
            }else{
            }*/

        } catch (Exception e) {
            e.printStackTrace();
        }
        return respMessage;
    }



    /**
     * 文本事件
     * */
    public  String sendCustomerTextMessage(String openid,String text,String accessToken)throws Exception{
        Map<String,Object> map_content = new HashMap<>();
        map_content.put("content",text);
        Map<String,Object> map = new HashMap<>();
        map.put("touser",openid);
        map.put("msgtype","text");
        map.put("text",map_content);
        String content =  JSON.toJSONString(map);
        return HttpClientUtils.httpPost(SEND_URL+"?access_token="+accessToken,content);

    }

    /**
     * 会话事件
     * */
    public  String sendFirstMessage(String openid, String text,String accessToken) throws Exception {

        Map<String, Object> map_content = new HashMap<>();
        map_content.put("content", text);

        Map<String, Object> map = new HashMap<>();
        map.put("touser", openid);
        map.put("msgtype", "text");
        map.put("text", map_content);

        String content = JSON.toJSONString(map);
        return HttpClientUtils.httpPost(SEND_URL + "?access_token=" + accessToken, content);
    }

    /***
     * 文档地址：https://mp.weixin.qq.com/debug/wxadoc/dev/api/custommsg/conversation.html
     * 发送的图片消息
     */
    public  String sendCustomerImageMessage (String openid, String mediaId,String accessToken)throws Exception{
        Map<String, Object> map_content = new HashMap<>();
        map_content.put("media_id", mediaId);
        Map<String, Object> map = new HashMap<>();

        map.put("touser", openid);
        map.put("msgtype", "image");

        map.put("image", map_content);
        String content = JSON.toJSONString(map);
        return HttpClientUtils.httpPost(SEND_URL + "?access_token=" + accessToken, content);
    }


    /***
     * 文档地址：https://mp.weixin.qq.com/debug/wxadoc/dev/api/custommsg/conversation.html
     * 转发至人工客服 现在默认都为人工客服
     */
    public  String switchCustomerService  (String fromUserName, String toUserName,Map requestMap)throws Exception{
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("ToUserName",fromUserName);
        resultMap.put("FromUserName",toUserName);
        resultMap.put("CreateTime", requestMap.get("CreateTime"));
        resultMap.put("MsgType","transfer_customer_service");
        String json = JSON.toJSONString(resultMap);
        JSONObject result = JSONObject.parseObject(json);
        logger.info("POST   result"  +  result);
        return result.toString();
    }

    public String getBeforeByHourTime(int ihour){
        String returnstr = "";
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - ihour);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        returnstr = df.format(calendar.getTime());
        return returnstr;
    }
}
